package com.gf.service;

import com.gf.client.StorageClient;
import com.gf.entity.Account;
import com.gf.mapper.AccountMapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
@RequiredArgsConstructor(onConstructor_={@Autowired})
public class AccountService {

    private static final String ERROR_USER_ID = "1002";

    private final AccountMapper accountMapper;

    private final StorageClient storageClient;

//    @GlobalTransactional(rollbackFor = Exception.class)
    public void debit(String userId , BigDecimal num) {
        Account account = accountMapper.selectByUserId(userId);
        account.setMoney(account.getMoney().subtract(num));
        accountMapper.updateById(account);

//        if (ERROR_USER_ID.equals(userId)) {
//            throw new RuntimeException("account branch exception");
//        }

        storageClient.b2c(userId, num);
    }

    public void c2b(String userId , BigDecimal num) {
        Account account = accountMapper.selectByUserId(userId);
        account.setMoney(account.getMoney().subtract(num));
        accountMapper.updateById(account);
    }

    @GlobalTransactional(rollbackFor = Exception.class)
    public void subById(String userId , BigDecimal num) {
        Account account = accountMapper.selectByUserId(userId);
        account.setMoney(account.getMoney().subtract(num));
        accountMapper.updateById(account);
    }

//    @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(rollbackFor = Exception.class)
    public void subById2(String userId , BigDecimal num) {
        Account account = accountMapper.selectByUserId(userId);
        account.setMoney(account.getMoney().subtract(num));
        accountMapper.updateById(account);
    }

}
